from __init__ import BaseResponse, log, ReturnResponse
from fastapi import (
    APIRouter, Depends, HTTPException
)
from .permissions import PermissionService
from .schemas import PermissionCreate, PermissionUpdate
from utils.mysql import get_session

router = APIRouter(prefix="/permissions", tags=["权限管理"])

@router.get("/body/{b_id}", response_model=BaseResponse)
def body(b_id: int):
    return {"code": 200, "data": b_id, "message": "body"}

@router.post("/post", response_model=BaseResponse)
async def create_permission(
    permission: PermissionCreate,
):
    db = get_session('dev')
    log.info("success", extra={"endpoint": "/permissions/post"})
    return await PermissionService.create_permission(db, permission)

@router.get("/single/{permission_id}", response_model=BaseResponse)
async def read_permission(
    permission_id: int
):
    db = get_session('dev')
    log.info("success", extra={"endpoint": f"/permissions/get/{permission_id}"})
    return await PermissionService.get_permission(db, permission_id)

@router.put("/{permission_id}", response_model=BaseResponse)
async def update_permission(
    permission_id: int,
    update_data: PermissionUpdate,
):
    db = get_session('dev')
    log.info("success", extra={"endpoint": f"/permissions/put/{permission_id}"} )
    return await PermissionService.update_permission(
        db, permission_id, update_data
    )

@router.delete("/{permission_id}", response_model=BaseResponse)
async def delete_permission(
    permission_id: int
):
    db = get_session('dev')
    try:
        se = await PermissionService.delete_permission(db, permission_id)
        log.info({"message": "权限已删除"})
        if se:
            log.info("success", extra={"endpoint": f"/permissions/delete/{permission_id}"})
            return ReturnResponse(data={"message": "权限已删除"})
        else:
            log.error("error", extra={"endpoint": f"/permissions/delete/{permission_id}"})
            return {"message": "权限删除失败"}
    except HTTPException as e:
        log.error(f"{str(e)}", extra={"endpoint": f"/permissions/delete/{permission_id}"})
        return ReturnResponse(code=e.status_code, data={"message": str(e.detail)})

@router.get("/list", response_model=BaseResponse)
async def list_permissions(
    skip: int = 0,
    limit: int = 100,
    include_inactive: bool = False,
):
    db = get_session('dev')
    res = await PermissionService.list_permissions(
        db, skip, limit, include_inactive
    )
    log.info("success", extra={"endpoint": "/permissions/list"})
    return ReturnResponse(data=res)